package thread.threadpool;

import java.util.concurrent.*;

/**
 * @author liweimin
 * @date 2021/5/24 16:15
 * @since
 */
public class Test07 {
    private static class MyThreadPoolExecutor extends ThreadPoolExecutor {

        public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
            super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        }

        @Override
        public Future<?> submit(Runnable task) {
            return super.submit(warp(task, new Exception("客户端异常")));
        }

        //定义方法对执行的任务进行包装
        public Runnable warp(Runnable task, Exception exception) {
            return () -> {
                try {
                    task.run();
                } catch (Exception e) {
                    exception.printStackTrace();
                    throw e;
                }
            };
        }
    }

    private static class DivideTask implements Runnable {
        private int x;
        private int y;

        public DivideTask(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "计算：" + x + " / " + y + " = " + (x / y));
        }
    }

    public static void main(String[] args) {
//        Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.out.println(t.getName() + "发生了异常：" + e.getMessage()));
        ThreadPoolExecutor threadPoolExecutor = new MyThreadPoolExecutor(0, Integer.MAX_VALUE, 0, TimeUnit.SECONDS, new SynchronousQueue<>());

        for (int i = 0; i < 5; i++) {
            //10/0 异常被吃掉
            threadPoolExecutor.submit(new DivideTask(10, i));
        }
    }
}
